import os
import json
from typing import Dict, List, Optional
from dataclasses import dataclass, asdict

@dataclass
class ColumnInfo:
    name: str
    type: str
    length: Optional[int] = None
    nullable: bool = True
    primary_key: bool = False

@dataclass
class TableInfo:
    name: str
    columns: List[ColumnInfo]
    primary_key: List[str]

class CatalogManager:
    def __init__(self, catalog_dir: str = "catalog"):
        self.catalog_dir = catalog_dir
        self.tables: Dict[str, TableInfo] = {}
        self._ensure_catalog_dir()
        self._load_catalog()
    
    def _ensure_catalog_dir(self):
        """确保目录存在"""
        if not os.path.exists(self.catalog_dir):
            os.makedirs(self.catalog_dir)
    
    def _load_catalog(self):
        """加载所有表定义"""
        if not os.path.exists(self.catalog_dir):
            return
        
        for filename in os.listdir(self.catalog_dir):
            if filename.endswith('.json'):
                table_name = filename[:-5]  # 移除.json后缀
                with open(os.path.join(self.catalog_dir, filename), 'r') as f:
                    data = json.load(f)
                    columns = [ColumnInfo(**col) for col in data['columns']]
                    self.tables[table_name] = TableInfo(
                        name=data['name'],
                        columns=columns,
                        primary_key=data['primary_key']
                    )
    
    def create_table(self, table_info: TableInfo) -> bool:
        """创建新表"""
        if table_info.name in self.tables:
            return False
        
        # 保存表定义到文件
        filename = os.path.join(self.catalog_dir, f"{table_info.name}.json")
        with open(filename, 'w') as f:
            json.dump(asdict(table_info), f, indent=2)
        
        # 添加到内存中的表目录
        self.tables[table_info.name] = table_info
        return True
    
    def get_table(self, table_name: str) -> Optional[TableInfo]:
        """获取表信息"""
        return self.tables.get(table_name)
    
    def drop_table(self, table_name: str) -> bool:
        """删除表"""
        if table_name not in self.tables:
            return False
        
        # 删除表定义文件
        filename = os.path.join(self.catalog_dir, f"{table_name}.json")
        if os.path.exists(filename):
            os.remove(filename)
        
        # 从内存中移除
        del self.tables[table_name]
        return True
    
    def table_exists(self, table_name: str) -> bool:
        """检查表是否存在"""
        return table_name in self.tables